package com.yuan.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.yuan.dao"}, sqlSessionFactoryRef = "kylin2SqlSessionFactory")
public class Kylin2DataSourceConfig {
    //主数据源mapper xml文件夹路径
    private static final String MAPPER_LOCAL = "classpath:mapper/*.xml";

    @ConfigurationProperties("spring.datasource.druid.kylin2")
    @Bean(name = "kylin2DataSource")
    public DruidDataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "kylin2TransactionManager")
    public DataSourceTransactionManager kylin2TransactionManager() {
        return new DataSourceTransactionManager(druidDataSource());
    }

    @Bean(name = "kylin2SqlSessionFactory")
    public SqlSessionFactory kylin2SqlSessionFactory(@Qualifier("kylin2DataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCAL));
        return sessionFactoryBean.getObject();
    }
}